package com.dbg.utils;

import com.dbg.entity.Language;
import com.dbg.entity.ResultEntity;
import com.dbg.entity.ResultSet;
import com.dbg.entity.TestSet;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;

public class FileUtils {

    // 根据文件扩展名数据集、路径，获取指定文件集合
    public static List<String> iterationFile(String path, final Set<String> fileExtensions, HashMap<String, Integer> sortRule) throws IOException {
        final List<String> fileNameList = new ArrayList<>();

        Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String fileName = file.toString();
                for (String fileExtension : fileExtensions) {
                    if (fileName.endsWith(fileExtension)) {
                        fileNameList.add(fileName);
                        break;
                    }
                }
                return super.visitFile(file, attrs);
            }
        });

        return sortFilesByExtension(fileNameList, sortRule);
    }

    public static ResultEntity fileOSToTxtFile(BufferedWriter writer, List<String> codeFileList, List<Language> languages, List<String> patterns) {
        try {
            // 遍历加入文档代码内容
            for (String codeFile : codeFileList) {
                String content = new String(Files.readAllBytes(Paths.get(codeFile)));
                content = TextUtils.removeComments(content, languages, patterns, FileUtils.getFileExtension(codeFile));

                // 遍历加入每行代码
                for (String line : content.split("\n")) {
                    if (!line.trim().isEmpty()) {
                        writer.write(line);
                    }
                }

            }
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            return ResultSet
                    .ERROR
                    .setMessage("msg", "生成临时txt文件失败！");
        }
        return ResultSet.SUCCESS;
    }

    // 提取文件的后缀名
    public static String getFileExtension(String filePath) {
        int lastIndexOfDot = filePath.lastIndexOf('.');
        if (lastIndexOfDot == -1) {
            return ""; // 没有后缀名
        }
        return filePath.substring(lastIndexOfDot);
    }

    // 对文件列表按照权重规则进行排序
    public static List<String> sortFilesByExtension(List<String> fileList, final HashMap<String, Integer> sortRule) {
        Collections.sort(fileList, new Comparator<String>() {
            @Override
            public int compare(String file1, String file2) {
                String ext1 = getFileExtension(file1);
                String ext2 = getFileExtension(file2);

                // 获取后缀的权重值，默认为 Integer.MAX_VALUE (排在最后)
                Integer weight1 = sortRule.get(ext1);
                Integer weight2 = sortRule.get(ext2);
                if (weight1 == null) {
                    weight1 = Integer.MAX_VALUE;
                }
                if (weight2 == null) {
                    weight2 = Integer.MAX_VALUE;
                }

                // 按权重排序
                return Integer.compare(weight1, weight2);
            }
        });
        return fileList;
    }

    // 扫描docx文件的内容，解析为字符串列表
    public static List<String> scanDocxToList(String path) {
        List<String> lines = new ArrayList<>();

        try (XWPFDocument docx = new XWPFDocument(new FileInputStream(path))) {
            for (XWPFParagraph paragraph : docx.getParagraphs()) {
                String line = paragraph.getText().replaceAll(" ", "\u00A0").trim(); // 使用不间断空格替代常规空格，并去掉前后空格
                if (!line.isEmpty()) {
                    lines.add(line);
                }
            }
        } catch (IOException e) {
            System.err.println("读取临时docx文件时出错: " + e.getMessage());
        }

        return lines;
    }

    // 扫描txt文件的内容，解析为字符串列表
    public static List<String> scanTxtToList(String path) {
        List<String> lines = new ArrayList<>();

        // 使用 try-with-resources 语句确保 BufferedReader 在使用后被正确关闭
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;

            // 逐行读取文件内容
            while ((line = reader.readLine()) != null) {
                lines.add(line); // 将每行内容添加到 List 中
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return lines;
    }

    // 扫描pdf文件的内容，解析为字符串列表
    public static List<String> scanPdfToList(String path) throws IOException {
        List<String> lines = new ArrayList<>();

        // 使用 PdfReader 读取 PDF 文件
        PdfReader reader = new PdfReader(path);
        PdfDocument pdfDocument = new PdfDocument(reader);

        // 遍历 PDF 中的每一页
        for (int i = 1; i <= pdfDocument.getNumberOfPages(); i++) {
            // 提取页面内容
            String pageContent = PdfTextExtractor.getTextFromPage(pdfDocument.getPage(i));

            // 按换行符分割内容
            String[] pageLines = pageContent.split("\n");
            // 去除每行前后空格并加入列表
            lines.addAll(Arrays.asList(pageLines));
        }

        for (String line : lines) {
            System.out.println(line);
        }

        // 关闭文档
        pdfDocument.close();
        return lines;
    }

    public static ResultEntity deleteFile(String path) {
        Path file = Paths.get(path);

        try {
            Files.delete(file);
        } catch (IOException ioException) {
            ioException.printStackTrace();
            return ResultSet
                    .ERROR
                    .setMessage("msg", "文件删除是否，文件可能被其他程序占用中");
        }

        return ResultSet
                .SUCCESS;
    }

    // 测试方法
    public static void main(String[] args) {
        Set<String> strings = TestSet.javaLanguageSet();
        HashMap<String, Integer> sortRule = TestSet.javaSortRule();

        try {
            List<String> strings1 = FileUtils
                    .iterationFile("C:\\Users\\someo\\Desktop\\bs\\bs\\intelligent_job_system-master", strings, sortRule);

            for (String s : strings1) {
                System.out.println(s);
            }
        } catch (IOException e) {
            System.out.println("文件读取异常");
        }

    }

}
